package com.liu.jd_demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.liu.jd_demo.pojo.Content;
import com.liu.jd_demo.service.ContentService;
import com.liu.jd_demo.utils.HtmlUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author QS.Liu
 * @date 2020/6/29/21:32
 */
@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    RestHighLevelClient restHighLevelClient;


    @Override
    //解析数据放入 es 索引中
    public Boolean parseContent(String keyword) {
        List<Content> contents = null;
        try {
            contents = new HtmlUtils().parseJD(keyword);
            //把查询放入到 es中
            BulkRequest bulkRequest = new BulkRequest();
            bulkRequest.timeout("2m");

            for (int i = 0; i < contents.size(); i++) {
                bulkRequest.add(
                        new IndexRequest("jd_goods")
                                .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
                );
            }
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return !bulk.hasFailures();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> searchPage(String keyword, Integer page, Integer size) {
        if (page < 1) {
            page = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        searchSourceBuilder.from(page);
        searchSourceBuilder.size(size);

        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));

        //执行搜索
        try {
            searchRequest.source(searchSourceBuilder);
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            ArrayList<Map<String,Object>> arrayList = new ArrayList<>();
            //解析结果
            SearchHits hits = search.getHits();
            for (SearchHit documentFields : hits.getHits()) {
                arrayList.add(documentFields.getSourceAsMap());
            }
            return arrayList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> searchhighPage(String keyword, Integer page, Integer size) {
            if (page < 1) {
                page = 1;
            }
            //条件搜索
            SearchRequest searchRequest = new SearchRequest("jd_goods");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //分页
            searchSourceBuilder.from(page);
            searchSourceBuilder.size(size);

            //精准匹配
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
            searchSourceBuilder.query(termQueryBuilder);
            searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));

            //高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("title");
            highlightBuilder.requireFieldMatch(false); //是否多个高亮
            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");
            searchSourceBuilder.highlighter(highlightBuilder);

            //执行搜索
            try {

                searchRequest.source(searchSourceBuilder);
                SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
                ArrayList<Map<String,Object>> arrayList = new ArrayList<>();
                //解析结果
                SearchHits hits = search.getHits();
                for (SearchHit documentFields : hits.getHits()) {
                    //解析高亮的字段
                    Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
                    HighlightField title = highlightFields.get("title");
                    Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();//这是原来的结果
                    if (title != null){
                        Text[] fragments = title.fragments();
                        String n_title = "";
                        for (Text fragment : fragments) {
                            n_title += fragment;
                        }
                        sourceAsMap.put("title",n_title);//替换 title
                    }

                    arrayList.add(sourceAsMap);
                }
                return arrayList;

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;

    }

}
